"""
音频流实体模型
"""

from sqlalchemy import (
    Column, String, Text, Integer, Float, Boolean, 
    JSON, ForeignKey, Enum as SQLEnum, DateTime
)
from sqlalchemy.orm import relationship, declarative_base
from datetime import datetime
from enum import Enum
import uuid

from ..core.database import Base


class StreamStatus(Enum):
    """流状态"""
    INITIALIZING = "initializing"   # 初始化中
    BUFFERING = "buffering"         # 缓冲中
    PLAYING = "playing"             # 播放中
    PAUSED = "paused"               # 暂停
    STOPPED = "stopped"             # 停止
    ERROR = "error"                 # 错误
    COMPLETED = "completed"         # 完成


class StreamType(Enum):
    """流类型"""
    TTS_STREAM = "tts_stream"       # TTS语音流
    AUDIOBOOK_STREAM = "audiobook_stream"  # 有声读物流
    FILE_STREAM = "file_stream"     # 文件音频流
    CUSTOM_STREAM = "custom_stream" # 自定义流


class AudioStream(Base):
    """音频流模型"""
    __tablename__ = "audio_streams"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    
    # 流基本信息
    title = Column(String(200), nullable=True)
    description = Column(Text, nullable=True)
    stream_type = Column(SQLEnum(StreamType), nullable=False, index=True)
    
    # 流状态
    status = Column(SQLEnum(StreamStatus), default=StreamStatus.INITIALIZING, index=True)
    progress = Column(Float, default=0.0)  # 播放进度 0-1
    
    # 音频配置
    sample_rate = Column(Integer, default=22050)  # 采样率
    channels = Column(Integer, default=1)         # 声道数
    format = Column(String(10), default="wav")    # 音频格式
    bitrate = Column(Integer, default=128)        # 比特率
    
    # 缓冲配置
    buffer_size = Column(Integer, default=8192)    # 缓冲区大小
    max_buffers = Column(Integer, default=10)      # 最大缓冲数量
    preload_buffers = Column(Integer, default=3)   # 预加载缓冲数量
    
    # 播放控制
    current_position = Column(Float, default=0.0)   # 当前位置(秒)
    duration = Column(Float, default=0.0)           # 总时长(秒)
    playback_rate = Column(Float, default=1.0)       # 播放速率
    volume = Column(Float, default=1.0)              # 音量
    
    # 质量控制
    quality_level = Column(String(20), default="medium")  # 质量等级
    auto_quality = Column(Boolean, default=False)         # 自动质量调节
    
    # 流媒体设置
    allow_seek = Column(Boolean, default=True)          # 允许拖拽
    allow_speed = Column(Boolean, default=True)         # 允许调速
    is_live = Column(Boolean, default=False)            # 是否直播流
    
    # 关联信息
    audiobook_id = Column(String, ForeignKey("audiobooks.id"), nullable=True, index=True)
    user_id = Column(String, nullable=False, index=True)
    
    # 会话信息
    session_id = Column(String, nullable=True, index=True)
    websocket_connection_id = Column(String, nullable=True)
    
    # 统计信息
    bytes_sent = Column(Integer, default=0)          # 已发送字节数
    chunks_sent = Column(Integer, default=0)         # 已发送块数
    buffer_underruns = Column(Integer, default=0)    # 缓冲区耗尽次数
    quality_changes = Column(Integer, default=0)     # 质量变化次数
    reconnections = Column(Integer, default=0)        # 重连次数
    
    # 元数据
    stream_metadata = Column(JSON, nullable=True)    # 流元数据
    client_info = Column(JSON, nullable=True)        # 客户端信息
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    started_at = Column(DateTime, nullable=True)
    completed_at = Column(DateTime, nullable=True)
    last_activity_at = Column(DateTime, default=datetime.utcnow)
    
    # 关系
    audiobook = relationship("AudioBook", back_populates="streams")
    quality_events = relationship("StreamQualityEvent", back_populates="stream", cascade="all, delete-orphan")
    connection_logs = relationship("StreamConnectionLog", back_populates="stream", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<AudioStream(id='{self.id}', type='{self.stream_type.value}', status='{self.status.value}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "title": self.title,
            "description": self.description,
            "stream_type": self.stream_type.value,
            "status": self.status.value,
            "progress": self.progress,
            "sample_rate": self.sample_rate,
            "channels": self.channels,
            "format": self.format,
            "bitrate": self.bitrate,
            "buffer_size": self.buffer_size,
            "max_buffers": self.max_buffers,
            "preload_buffers": self.preload_buffers,
            "current_position": self.current_position,
            "duration": self.duration,
            "playback_rate": self.playback_rate,
            "volume": self.volume,
            "quality_level": self.quality_level,
            "auto_quality": self.auto_quality,
            "allow_seek": self.allow_seek,
            "allow_speed": self.allow_speed,
            "is_live": self.is_live,
            "audiobook_id": self.audiobook_id,
            "user_id": self.user_id,
            "session_id": self.session_id,
            "websocket_connection_id": self.websocket_connection_id,
            "bytes_sent": self.bytes_sent,
            "chunks_sent": self.chunks_sent,
            "buffer_underruns": self.buffer_underruns,
            "quality_changes": self.quality_changes,
            "reconnections": self.reconnections,
            "metadata": self.metadata,
            "client_info": self.client_info,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "started_at": self.started_at.isoformat() if self.started_at else None,
            "completed_at": self.completed_at.isoformat() if self.completed_at else None,
            "last_activity_at": self.last_activity_at.isoformat() if self.last_activity_at else None
        }


class StreamQualityEvent(Base):
    """流质量事件模型"""
    __tablename__ = "stream_quality_events"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    stream_id = Column(String, ForeignKey("audio_streams.id"), nullable=False, index=True)
    
    # 事件信息
    event_type = Column(String(50), nullable=False)        # 事件类型
    old_quality = Column(String(20), nullable=True)        # 原始质量
    new_quality = Column(String(20), nullable=True)        # 新质量
    reason = Column(Text, nullable=True)                   # 变化原因
    
    # 网络指标
    bandwidth_kbps = Column(Float, default=0.0)             # 带宽
    latency_ms = Column(Float, default=0.0)                 # 延迟
    packet_loss_rate = Column(Float, default=0.0)          # 丢包率
    jitter_ms = Column(Float, default=0.0)                 # 抖动
    
    # 缓冲状态
    buffer_health = Column(Float, default=0.5)              # 缓冲健康度
    buffer_fill_ratio = Column(Float, default=0.0)          # 缓冲填充率
    
    # 系统指标
    cpu_usage = Column(Float, default=0.0)                  # CPU使用率
    memory_usage = Column(Float, default=0.0)               # 内存使用率
    
    # 时间戳
    timestamp = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    # 关系
    stream = relationship("AudioStream", back_populates="quality_events")
    
    def __repr__(self):
        return f"<StreamQualityEvent(id='{self.id}', stream_id='{self.stream_id}', event_type='{self.event_type}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "stream_id": self.stream_id,
            "event_type": self.event_type,
            "old_quality": self.old_quality,
            "new_quality": self.new_quality,
            "reason": self.reason,
            "bandwidth_kbps": self.bandwidth_kbps,
            "latency_ms": self.latency_ms,
            "packet_loss_rate": self.packet_loss_rate,
            "jitter_ms": self.jitter_ms,
            "buffer_health": self.buffer_health,
            "buffer_fill_ratio": self.buffer_fill_ratio,
            "cpu_usage": self.cpu_usage,
            "memory_usage": self.memory_usage,
            "timestamp": self.timestamp.isoformat() if self.timestamp else None
        }


class StreamConnectionLog(Base):
    """流连接日志模型"""
    __tablename__ = "stream_connection_logs"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    stream_id = Column(String, ForeignKey("audio_streams.id"), nullable=False, index=True)
    
    # 连接信息
    connection_type = Column(String(20), nullable=False)     # 连接类型：websocket, http
    client_ip = Column(String(45), nullable=True)           # 客户端IP
    user_agent = Column(Text, nullable=True)                # 用户代理
    connection_id = Column(String, nullable=True)          # 连接ID
    
    # 连接状态
    event_type = Column(String(20), nullable=False)          # 事件类型：connect, disconnect, error
    status_code = Column(Integer, nullable=True)             # 状态码
    error_message = Column(Text, nullable=True)              # 错误信息
    
    # 性能指标
    connection_time = Column(Float, default=0.0)            # 连接时间(秒)
    bytes_transferred = Column(Integer, default=0)          # 传输字节数
    avg_bitrate = Column(Float, default=0.0)                # 平均比特率
    
    # 客户端信息
    client_config = Column(JSON, nullable=True)             # 客户端配置
    
    # 时间戳
    timestamp = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    # 关系
    stream = relationship("AudioStream", back_populates="connection_logs")
    
    def __repr__(self):
        return f"<StreamConnectionLog(id='{self.id}', stream_id='{self.stream_id}', event_type='{self.event_type}')>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "stream_id": self.stream_id,
            "connection_type": self.connection_type,
            "client_ip": self.client_ip,
            "user_agent": self.user_agent,
            "connection_id": self.connection_id,
            "event_type": self.event_type,
            "status_code": self.status_code,
            "error_message": self.error_message,
            "connection_time": self.connection_time,
            "bytes_transferred": self.bytes_transferred,
            "avg_bitrate": self.avg_bitrate,
            "client_config": self.client_config,
            "timestamp": self.timestamp.isoformat() if self.timestamp else None
        }


class StreamBuffer(Base):
    """流缓冲模型"""
    __tablename__ = "stream_buffers"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    stream_id = Column(String, ForeignKey("audio_streams.id"), nullable=False, index=True)
    
    # 缓冲信息
    sequence_number = Column(Integer, nullable=False)       # 序列号
    size_bytes = Column(Integer, default=0)               # 大小(字节)
    duration_ms = Column(Float, default=0.0)              # 时长(毫秒)
    
    # 缓冲状态
    status = Column(String(20), default="pending")         # 状态：pending, sent, dropped
    checksum = Column(String(64), nullable=True)         # 校验和
    
    # 时间信息
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    sent_at = Column(DateTime, nullable=True)
    
    # 关系
    stream = relationship("AudioStream")
    
    def __repr__(self):
        return f"<StreamBuffer(id='{self.id}', stream_id='{self.stream_id}', sequence={self.sequence_number})>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "stream_id": self.stream_id,
            "sequence_number": self.sequence_number,
            "size_bytes": self.size_bytes,
            "duration_ms": self.duration_ms,
            "status": self.status,
            "checksum": self.checksum,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "sent_at": self.sent_at.isoformat() if self.sent_at else None
        }


class StreamSession(Base):
    """流会话模型"""
    __tablename__ = "stream_sessions"
    
    id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    user_id = Column(String, nullable=False, index=True)
    
    # 会话信息
    title = Column(String(200), nullable=True)
    session_type = Column(String(20), default="single")    # single, playlist, radio
    
    # 会话状态
    is_active = Column(Boolean, default=True)
    auto_play = Column(Boolean, default=False)
    repeat_mode = Column(String(10), default="none")       # none, one, all
    
    # 播放列表
    stream_ids = Column(JSON, nullable=True)               # 流ID列表
    current_index = Column(Integer, default=0)              # 当前索引
    
    # 会话统计
    total_playtime = Column(Float, default=0.0)            # 总播放时间
    streams_played = Column(Integer, default=0)            # 播放的流数量
    
    # 客户端信息
    client_info = Column(JSON, nullable=True)
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    last_activity_at = Column(DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f"<StreamSession(id='{self.id}', user_id='{self.user_id}', active={self.is_active})>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "user_id": self.user_id,
            "title": self.title,
            "session_type": self.session_type,
            "is_active": self.is_active,
            "auto_play": self.auto_play,
            "repeat_mode": self.repeat_mode,
            "stream_ids": self.stream_ids,
            "current_index": self.current_index,
            "total_playtime": self.total_playtime,
            "streams_played": self.streams_played,
            "client_info": self.client_info,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "last_activity_at": self.last_activity_at.isoformat() if self.last_activity_at else None
        }
